package com.zdd.ehe.util;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @title:JwtUtil
 * @author:ZhuiZhu
 * @description:生成token
 * @createDate: 2023/3/12  19:13
 */
@Component
public class JwtUtil {
    // 有效期
    private static final long JWT_EXPTRE = 24*60*60*1000L; // 24小时有效时间
    // 令牌密钥
    private static final String JWT_KEY = "YGW232WYi846";

    /**
     * 创建token
     * @param data
     * @return
     */
    public String createToken(Object data){
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expTime = currentTime + JWT_EXPTRE;
        // 构建JWT
        JwtBuilder builder = Jwts.builder().setId(UUID.randomUUID()+" ")
                .setSubject(JSON.toJSONString(data))
                .setIssuer("system")
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS256, encodeSecret(JWT_KEY)) //对称加密
                .setExpiration(new Date(expTime));

        return builder.compact();
    }

    /**
     * JWT_KEY 转Base64编码
     * @param key
     * @return
     */
    private SecretKey encodeSecret(String key){
        // Base64转码
        byte[] encode = Base64.getEncoder().encode(key.getBytes());
        SecretKeySpec spec = new SecretKeySpec(encode, 0, encode.length, "AES");
        return spec;
    }

    /**
     * 解码token
     * @param token
     * @return
     */
    public Claims parseToken(String token){
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return body;
    }

    /**
     * 解码token返回对象
     * @param token
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T parseToken(String token,Class<T> clazz){
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return JSON.parseObject(body.getSubject(),clazz);
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

}
